package cn.sirun.com.fca.account.view.impl;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tencent.cloud.iov.kernel.constant.StatusCode;
import com.tencent.cloud.iov.kernel.model.BaseResponse;
import com.tencent.cloud.iov.router.Router;
import com.tencent.cloud.iov.util.ActivityUtils;
import com.tencent.cloud.iov.util.PatternMatchingUtils;
import com.tencent.cloud.iov.util.ResourcesUtils;
import com.tencent.cloud.iov.util.SRPUtils;
import com.tencent.cloud.iov.util.lifecycle.ActivityStackManager;
import com.tencent.cloud.iov.util.storage.TXCacheManager;
import com.tencent.cloud.uikit.ui.widget.IovToolbar;
import com.tencent.cloud.uikit.utils.SystemUiUtils;
import com.tencent.cloud.uikit.widget.edittext.LineEditText;
import com.tencent.cloud.uikit.widget.edittext.PasswordEditText;

import cn.sirun.com.fca.account.R;
import cn.sirun.com.fca.account.constant.AccountActivityConst;
import cn.sirun.com.fca.account.constant.AccountCommonConst;
import cn.sirun.com.fca.account.constant.AccountIntentConst;
import cn.sirun.com.fca.account.constant.CaptchaConst;
import cn.sirun.com.fca.account.model.login.LoginResponse;
import cn.sirun.com.fca.account.presenter.IPasswordPresenter;
import cn.sirun.com.fca.account.presenter.impl.PasswordPresenter;
import cn.sirun.com.fca.account.service.LoginManager;
import cn.sirun.com.fca.account.uitl.AccountStatusUtils;
import cn.sirun.com.fca.account.uitl.IntentUtils;
import cn.sirun.com.fca.account.view.IPasswordView;

public class PasswordFlowView extends AccountBaseLoadingFlowView<IPasswordPresenter> implements
        IPasswordView {

    private static final String TAG = PasswordFlowView.class.getSimpleName();

    private PasswordEditText mPassET, mRePassET;
    private ImageView mPromptIV, mRePromptIV, mStepIV;
    private TextView mPromptTV, mRePromptTV, mSubmitTV;
    private View mLineV, mReLineV;

    private int mFrom;
    private boolean mIsPhone;
    private String mPhoneNumber;

    public PasswordFlowView(Activity activity) {
        super(activity);
        mFrom = IntentUtils.getIntentFrom(getActivity().getIntent(), AccountIntentConst.REGISTER);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        setUpActionBar();
        initView();
    }


    @Override
    public void onSetPasswordResult(BaseResponse<LoginResponse> response) {
//        hideLoadingView();
//        int code = response.getCode();
//        if (StatusCode.SUCCESS == response.getCode()) {
//            LoginManager.getInstance().handleLoginSuccess(response.getData());
//            turnToMainActivity();
//        } else {
//            AccountStatusUtils.showToast(getActivity(), code);
//        }
        handleRegisterSetPassResult(response);
    }

    @Override
    public void onSetEmailPasswordResult(BaseResponse<LoginResponse> response) {
        handleRegisterSetPassResult(response);
    }

    @Override
    public void onResetPasswordResult(BaseResponse<Void> response) {
        hideLoadingView();
        if (StatusCode.SUCCESS == response.getCode()) {
            ActivityStackManager.getInstance().clearNumberStack(3);
        } else {
            AccountStatusUtils.showToast(getActivity(), response.getCode());
        }
    }

    private void handleRegisterSetPassResult(BaseResponse<LoginResponse> response) {
        hideLoadingView();
        int code = response.getCode();
        if (StatusCode.SUCCESS == response.getCode()) {
            LoginManager.getInstance().handleLoginSuccess(response.getData());
            turnToMainActivity();
        } else {
            AccountStatusUtils.showToast(getActivity(), code);
        }
    }

    public void turnToMainActivity() {
        ActivityStackManager.getInstance().clearStack();
        Intent intent = Router.fromPath(AccountActivityConst.Path.MAIN);
        ActivityUtils.startActivity(getActivity(), intent);
        getActivity().finish();
    }

    @Override
    protected IPasswordPresenter createPresenter() {
        return new PasswordPresenter();
    }

    private void setUpActionBar() {
        final IovToolbar toolbar = SystemUiUtils.showActionBar(
                getActivity(), "");
        if (mFrom == AccountIntentConst.REGISTER) {
            toolbar.setHomeAsUpText(R.string.tv_title_previous_step);
        }
    }

    private void initView() {
        setContentView(R.layout.register_pass_activity);
        final Activity activity = getActivity();
        mPassET = activity.findViewById(R.id.et_pass_number);
        mRePassET = activity.findViewById(R.id.et_repass_number);
        mPromptIV = activity.findViewById(R.id.iv_pass_prompt);
        mRePromptIV = activity.findViewById(R.id.iv_repass_prompt);
        mRePromptTV = activity.findViewById(R.id.tv_repass);
        mStepIV = activity.findViewById(R.id.iv_step_three);
        mPromptTV = activity.findViewById(R.id.tv_pass);
        mSubmitTV = activity.findViewById(R.id.tv_submit_login);
        mLineV = activity.findViewById(R.id.v_pass_line);
        mReLineV = activity.findViewById(R.id.v_repass_line);
        registerListener();
        initData(activity);
    }

    private void registerListener() {

        mPassET.setCheckFormatListener(new LineEditText.OnCheckFormatListener() {
            @Override
            public void onSuccess() {
                setPassLayoutBg(View.GONE, ResourcesUtils.getColor(R.color.login_input_text_color),
                        ResourcesUtils.getString(R.string.tv_title_input_pass), R.color.divider_bg_color);
            }

            @Override
            public void onFailed() {
                setPassLayoutBg(View.VISIBLE, ResourcesUtils.getColor(R.color.login_register_text_color),
                        ResourcesUtils.getString(R.string.tv_pass_notice), R.color.login_register_text_color);
            }
        });

        mPassET.setTextChangeListener(new LineEditText.OnTextChangeListener() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setConfirmBtnEnable();
            }
        });

        mRePassET.setTextChangeListener(new LineEditText.OnTextChangeListener() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setConfirmBtnEnable();
            }
        });

        mSubmitTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!checkFormat()) {
                    return;
                }
                sendSetPasswordRequest();
            }
        });

    }

    private void setPassLayoutBg(int visibility, int textColor, String text, int lineColor) {
        mPromptIV.setVisibility(visibility);
        mPromptTV.setTextColor(textColor);
        mPromptTV.setText(text);
        mLineV.setBackgroundResource(lineColor);
    }

    private void setRePassLayoutBg(int visibility, int textColor, String text, int lineColor) {
        mRePromptIV.setVisibility(visibility);
        mRePromptTV.setTextColor(textColor);
        mRePromptTV.setText(text);
        mReLineV.setBackgroundResource(lineColor);
    }

    private void setConfirmBtnEnable() {

        int passwordLength = mPassET.length();
        int reenterPasswordLength = mRePassET.length();

        boolean isEnable = (passwordLength >= PasswordEditText.MIN_LENGTH
                && reenterPasswordLength >= PasswordEditText.MIN_LENGTH);

        if (0 == reenterPasswordLength) {
            setRePassLayoutBg(View.GONE, ResourcesUtils.getColor(R.color.login_input_text_color),
                    ResourcesUtils.getString(R.string.tv_title_input_pass2), R.color.divider_bg_color);
        }

        if (0 == passwordLength) {
            setPassLayoutBg(View.GONE, ResourcesUtils.getColor(R.color.login_input_text_color),
                    ResourcesUtils.getString(R.string.tv_title_input_pass), R.color.divider_bg_color);
        }

        if (isEnable) {
            mSubmitTV.setBackgroundResource(R.drawable.s_btn_bg_border);
        } else {
            mSubmitTV.setBackgroundResource(R.drawable.s_btn_default_bg_border);
        }
        mSubmitTV.setEnabled(isEnable);
    }

    private boolean checkFormat() {
        String password = mPassET.getText().toString();
        String reEnterPassword = mRePassET.getText().toString();
        boolean isInputPasswordCorrect = PatternMatchingUtils.isPasswordCorrect(password);

        if (isInputPasswordCorrect) {
            if (password.equals(reEnterPassword)) {
                setRePassLayoutBg(View.GONE, ResourcesUtils.getColor(R.color.login_input_text_color),
                        ResourcesUtils.getString(R.string.tv_title_input_pass2), R.color.divider_bg_color);
                return true;
            } else {
                setRePassLayoutBg(View.VISIBLE, ResourcesUtils.getColor(R.color.login_register_text_color),
                        ResourcesUtils.getString(R.string.tv_title_input_pass_error), R.color.login_register_text_color);
                return false;
            }
        } else {
            setPassLayoutBg(View.VISIBLE, ResourcesUtils.getColor(R.color.login_register_text_color),
                    ResourcesUtils.getString(R.string.tv_pass_notice), R.color.login_register_text_color);
            return false;
        }
    }

    private void initData(Activity activity) {

        if (mFrom == AccountIntentConst.FORGET_PASSWORD) {
            mStepIV.setVisibility(View.GONE);
        }

        Intent intent = activity.getIntent();

        if (intent.hasExtra(AccountIntentConst.TELEPHONE)) {
            mPhoneNumber = intent.getStringExtra(AccountIntentConst.TELEPHONE);
            mIsPhone = PatternMatchingUtils.isTelephoneCorrect(mPhoneNumber);
        }
    }

    private void sendSetPasswordRequest() {
        showLoadingView();
        String password = mPassET.getText().toString();
        String salt = TXCacheManager.getInstance().get(SRPUtils.SRP_SALT);
        String group = TXCacheManager.getInstance().get(SRPUtils.SRP_GROUP);
        if (mIsPhone) {
            if (mFrom == AccountIntentConst.REGISTER) {
                getPresenter().setPassword(SRPUtils.encryptData(password, salt, group));
            } else if (mFrom == AccountIntentConst.FORGET_PASSWORD) {
                getPresenter().resetSetPassword(SRPUtils.encryptData(password, salt, group));
            }
        } else {
            if (mFrom == AccountIntentConst.REGISTER) {
                getPresenter().setEmialPassword(SRPUtils.encryptData(password, salt, group));
            } else if (mFrom == AccountIntentConst.FORGET_PASSWORD) {
                getPresenter().resetEmailSetPassword(SRPUtils.encryptData(password, salt, group));
            }

        }
    }
}
